#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    ui->treeWidget->setHeaderLabel("麦当劳");

    QTreeWidgetItem* item1 = new QTreeWidgetItem();
    item1->setText(0,"汉堡");
    ui->treeWidget->addTopLevelItem(item1);
    QTreeWidgetItem* item2 = new QTreeWidgetItem();
    item2->setText(0,"小食");
    ui->treeWidget->addTopLevelItem(item2);
    QTreeWidgetItem* item3 = new QTreeWidgetItem();
    item3->setText(0,"饮料");
    ui->treeWidget->addTopLevelItem(item3);
}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_pushButton_addTop_clicked()
{
    QString txt = ui->lineEdit->text();
    if(txt.isEmpty())
        return;
    QTreeWidgetItem* item = new QTreeWidgetItem();
    item->setText(0,txt);
    ui->treeWidget->addTopLevelItem(item);
}

void Widget::on_pushButton_add_clicked()
{
    QString txt = ui->lineEdit->text();
    if(txt.isEmpty())
        return;
    QTreeWidgetItem* itemParent = ui->treeWidget->currentItem();
    if(itemParent==nullptr)
        return;
    QTreeWidgetItem* itemChild = new QTreeWidgetItem();
    itemChild->setText(0,txt);
    itemParent->addChild(itemChild);
    itemParent->setExpanded(true);
}

void Widget::on_pushButton_del_clicked()
{
    QTreeWidgetItem* currentItem = ui->treeWidget->currentItem();
    if(currentItem==nullptr)
        return;
    QTreeWidgetItem* parent = currentItem->parent();
    if(parent==nullptr)
    {
        int index = ui->treeWidget->indexOfTopLevelItem(currentItem);
        ui->treeWidget->takeTopLevelItem(index);
    }
    else
        parent->removeChild(currentItem);
}
